package com.roast.services.my;

import com.roast.util.QueryObject;
import com.roast.domain.*;

public class GetAddressIMPL extends GeneralSO implements GetAddress {

    private Address address;
    private QueryObject queryObject;
    private DomainObject fromDB;

    @Override
    public int getAddress(Address address) {
        return new GetAddressIMPL().generalExecution(address);
    }

    @Override
    protected int executeSO(Object obj) {
        if (!setAddress(obj)) {
            return 10901;
        }
        setQueryObject();
        if (!readAddress()) {
            return 10902;
        }
        if (!copyObject(obj)) {
            return 10903;
        }

        return 10900;
    }

    private boolean setAddress(Object obj) {
        try {
            this.address = (Address) obj;
            return true;
        } catch (ClassCastException ex) {
            return false;
        }
    }

    private void setQueryObject() {
        queryObject = new QueryObject();
        queryObject.setDomaninObject(address);
    }

    private boolean readAddress() {
        fromDB = dbbr.readOneByID(queryObject);
        return queryObject.getSignal() == 10020;
    }

    private boolean copyObject(Object obj) {
        try {
            return ((Address) obj).copyObject(fromDB);
        } catch (ClassCastException ex) {
            return false;
        }
    }

    @Override
    protected boolean executeState(int signal) {
        switch (signal) {
            case 10900:
                showOperationState(signal, "_getAddress: You have successfully read addressing.");
                return true;
            case 10901:
                showOperationState(signal, "_getAddress:ERROR: Class cast exception.");
                return false;
            case 10902:
                showOperationState(signal, "_getAddress:ERROR: You fail to read addressing from database.");
                return false;
            case 10903:
                showOperationState(signal, "_addressToStar:ERROR: Fail to copy object.");
                return false;
        }
        return false;
    }

}
